package com.zhongxi.guoyuan.view.user;


import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.UserData;
import com.zhongxi.guoyuan.entity.user.UseInfo;
import com.zhongxi.guoyuan.entity.user.UserResult;
import com.zhongxi.guoyuan.entity.user.WeiXinLogin;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvRegister;
    private TextView tvForgot;
    private TextView tvLogin;
    private EditText etPhone;
    private EditText etPassword;
    private int position;
    private String type;
    private LinearLayout linearLogin;
    private Map<String, String> maps = new HashMap<>();
    private String mOpenid;


    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_login);
        initTitle();
        tvTitle.setText("会员登录");
        ivBack = (ImageView) findViewById(R.id.ivBack);
        tvRegister = (TextView) findViewById(R.id.tvRegister);
        tvForgot = (TextView) findViewById(R.id.tvForgot);
        tvLogin = (TextView) findViewById(R.id.tvLogin);
        etPhone = (EditText) findViewById(R.id.etPhone);
        etPassword = (EditText) findViewById(R.id.etPassword);
        linearLogin = (LinearLayout) findViewById(R.id.linear_wxLogin);
        position = getIntent().getIntExtra("position", 0);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvRegister.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvForgot.setOnClickListener(this);
        tvLogin.setOnClickListener(this);
        linearLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvRegister:
                startAct(RegisterActivity.class);
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvForgot:
                startAct(ForgotPasswordActivity.class);
                break;
            case R.id.tvLogin:
                login();
                break;
            case R.id.linear_wxLogin:
                type = "weixin";
                getServer(Url.WXAUTH, null, "", false, null, "get");
                break;
        }
    }

    private void wxLogin(final String authcode) {
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {

            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                //  o8sNlwgnjClXeZZzZ4xwdV041PuQ
                mOpenid = map.get("openid");
                MyApplication.getInstance().sharedPrefrences.edit().putString("wxname", map.get("name")).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("iconurl", map.get("iconurl")).commit();
                if (!TextUtils.isEmpty(mOpenid)) {
                    type = "login";
                    maps.clear();
                    maps.put("authcode", authcode);  //  ZDdhNGJlM2RlNzUyMWQ0Y4zuQZfqJWsHOlespsLqHkgL4CLWCUSLSkUEw7uPg!Dn
                    maps.put("openid", mOpenid);
                    getServer(Url.WXCHECK, maps, "", false, null, "post");
                } else {
                    showShortToast("授权登录失败");
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                showShortToast("授权登录失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                showShortToast("授权登录取消");
            }
        });
    }

    /**
     * 登录
     */
    private void login() {
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showShortToast("手机号不能为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else if (TextUtils.isEmpty(password)) {
            showShortToast("请输入密码");
        } else {
            maps.clear();
            maps.put("mobilenum", MyApplication.getInstance().descsc(phone));
            maps.put("pwd", MyApplication.getInstance().descsc(password));
            type = "login";
            getServer(Url.LOGIN, maps, "", false, null, "post");
        }
    }

    /**
     * userid: usr19805ac2017cdc010              usr32715ac1fde1e6452
     * appopenid:  o8sNlwgnjClXeZZzZ4xwdV041PuQ      o8sNlwjnhmTlI9tOBb-rvRRnC4YM
     *
     * @param response
     */

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if ("login".equals(type)) {
                System.out.println("login==" + response);
                UserResult result = gson.fromJson(response, UserResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getData() && !"".equals(result.getData())) {
                    UserData data = result.getData();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("phone", result.getData().getMphone()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("userid", result.getData().getId()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("username", result.getData().getUsername()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", result.getData().getShopname()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", result.getData().getAvatar()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("time", result.getData().getCtime()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", result.getData().getAppopenid()).commit();
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //股东
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(data.getIsshareholders())).commit();
                    }
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  // 消费收益人
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", "1".equals(data.getIsbeneficiary())).commit();
                    }
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //商家
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", "1".equals(data.getIsmerchants())).commit();
                    }

                    if (null != String.valueOf(data.getIspartner())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("partener", 1 == data.getIspartner()).commit();
                    }
                    if (TextUtils.isEmpty(data.getRegistrationid()) ||
                            (!TextUtils.isEmpty(data.getRegistrationid()) && !data.getRegistrationid().equals(JPushInterface.getRegistrationID(UiUtils.getContext())))) {
                        toMyServer(JPushInterface.getRegistrationID(UiUtils.getContext()));
                    }
                }
                if (null != result.getExtend() && !"".equals(result.getExtend())) {
                    UseInfo extend = result.getExtend();
                    if (null != extend.getInnercurrency() && !"".equals(extend.getInnercurrency())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("inner", extend.getInnercurrency()).commit();
                    }
                    if (null != extend.getRedbean() && !"".equals(extend.getRedbean())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("hd", DataUtil.formatDataSixPoint(extend.getRedbean())).commit();
                    }

                    if (null != extend.getSharesgains() && !"".equals(extend.getSharesgains())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("share", DataUtil.formatData(extend.getSharesgains())).commit();  //股份收益
                    }
                }
                if (position == 1) {
                    finish();
                    startAct(MainHomeActivity.class);
                } else {
                    finish();
                }
            } else if (type.equals("weixin")) {
                WeiXinLogin mWeiXinLogin = gson.fromJson(response, WeiXinLogin.class);
                MyApplication.getInstance().setSpValue(mWeiXinLogin.safeobj);
                String mDescsc = MyApplication.getInstance().parseSecutiryKey(mWeiXinLogin.data);
                if (!TextUtils.isEmpty(mWeiXinLogin.authcode)) {
                    if (CommonTool.checkWxExist(this)) {
                        wxLogin(mWeiXinLogin.authcode);
                    } else {
                        showShortToast(getString(R.string.noInstall_wx));
                    }
                }
            } else if ("registerid".equals(type)) {
                System.out.println("registerid==" + response);
                JSONObject mObject = new JSONObject(response);
                String mId = mObject.optString("id");  //注册极光id
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void toMyServer(String regId) {
        maps.clear();
        maps.put("registerid", regId);
        type = "registerid";
        getServer(Url.UPDREGISTERID, maps, "", false, null, "post");
    }

    @Override
    public void onBackPressed() {
        if (position == 1) {
            finish();
            startAct(MainHomeActivity.class);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
                MyApplication.getInstance().setSpValue(result.getSafeobj());

            if (result.getCode() == 1000) {
//                showShortToast("参数错误");
            } else if (result.getCode() == 1003) {
                showShortToast("用户已登录");
            } else if (result.getCode() == 4003) {
                showShortToast("密码错误");
            } else if (result.getCode() == 4004) {
                showShortToast("用户未注册，请先注册");
            } else if (result.getCode() == 1004) {   // 微信新用户未注册
                showShortToast("用户未注册，请先注册");
                MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", mOpenid).commit();
                Intent mIntent = new Intent(this, RegisterActivity.class);
                startActivity(mIntent);
                finish();
            } else if (result.getCode() == 1005) {   // 微信登录的老用户
                showShortToast("老用户,还没有注册手机号呦!");
                Intent mIntent = new Intent(this, RegisterActivity.class);
                if (!TextUtils.isEmpty(mOpenid)) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", mOpenid).commit();
                }
                mIntent.putExtra("useid", result.getId());
                startActivity(mIntent);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void processOldUser(String response) {
        super.processOldUser(response);   // 正常登录的老用户   code==4002
        try {
            Gson gson = new Gson();
            BaseResponse baseBean = gson.fromJson(response, BaseResponse.class);
            if (null != baseBean.getSafeobj() && !"".equals(baseBean.getSafeobj())) {
                MyApplication.getInstance().setSpValue(baseBean.getSafeobj());
            }
            showShortToast("您已注册，未设置密码，请先设置密码后登陆");
            Intent mIntent = new Intent(this, SetPasswordActivity.class);
            mIntent.putExtra("id", baseBean.getId());  // 用户id;
            startActivity(mIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
